package com.xzzz.common.wechat.log;

import com.xzzz.common.base.util.DateUtils;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.irda.tracker.core.Tracker;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 微信调用方法切面
 *
 * @author xzzz
 */
@Slf4j
@Aspect
@Component
public class WxLogAspect implements ApplicationContextAware {

    // spel表达式解析器
    private final SpelExpressionParser spelExpressionParser = new SpelExpressionParser();

    // 参数名发现器
    private final DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Around("@within(wxLog)")
    public Object aroundClass(ProceedingJoinPoint joinPoint, WxLog wxLog) throws Throwable {
        return around(joinPoint, wxLog);
    }

    @Around("@annotation(wxLog)")
    public Object aroundMethod(ProceedingJoinPoint joinPoint, WxLog wxLog) throws Throwable {
        return around(joinPoint, wxLog);
    }

    private Object around(ProceedingJoinPoint joinPoint, WxLog wxLog) throws Throwable {
        WxLogDTO log = createLog();

        Class<?> clazz = joinPoint.getTarget().getClass();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        if (wxLog != null) {
            log.setTag(wxLog.tag());
            log.setType(wxLog.type());
            log.setDesc(expression(wxLog.desc(),(MethodSignature) joinPoint.getSignature(), args));
        }

        log.setClassName(clazz.getSimpleName());
        log.setMethodName(methodName);
        try {
            log.setMethodParam(JsonUtil.toJson(args));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Object returnObj;
        try {
            returnObj = joinPoint.proceed(args);
            try {
                log.setMethodResult(JsonUtil.toJson(returnObj));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Throwable throwable) {
            log.setException(throwable.getMessage());
            log.setSuccess("FAIL");
            throw throwable;
        } finally {
            log.setEndTime(DateUtils.date());
            applicationContext.publishEvent(new WxLogEvent(log));
        }

        return returnObj;
    }

    private WxLogDTO createLog() {
        WxLogDTO WxLogDTO = new WxLogDTO();
        WxLogDTO.setTraceId(Tracker.getTraceId());
        WxLogDTO.setSuccess("SUCC");
        WxLogDTO.setBeginTime(DateUtils.date());
        return WxLogDTO;
    }

    private String expression(String desc, MethodSignature method, Object[] args) {
        if (method == null) {
            return desc;
        }
        // Spel表达式解析日志信息
        // 获得方法参数名数组
        try {
            String[] parameterNames = parameterNameDiscoverer.getParameterNames(method.getMethod());
            if (parameterNames != null && parameterNames.length > 0){
                EvaluationContext context = new StandardEvaluationContext();
                for (int i = 0; i < args.length; i++) {
                    context.setVariable(parameterNames[i], args[i]); // 替换spel里的变量值为实际值， 比如 #user -->  user对象
                }
                // 解析出实际的日志信息
                return Objects.requireNonNull(spelExpressionParser.parseExpression(desc).getValue(context)).toString();
            }
        } catch (Exception e) {
        }

        return desc;
    }
}
